package com.max.dao;

import com.max.base.BaseDao;
import com.max.entity.Userinfo;
import com.max.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;

public class UserinfoDao extends BaseDao<Userinfo> {

    private UserinfoDao() {
    }

    private static final UserinfoDao INSTANCE = new UserinfoDao();

    public static UserinfoDao getInstance() {
        return INSTANCE;
    }


    @Override
    public List<Userinfo> selectList(Userinfo userinfo) {
        return super.queryExecute(
                Userinfo.class,
                "select * from userinfo where 1=1 "
                        + (CommonUtils.isNotBlank(userinfo.getUsername()) ? "and username like concat('%', ?, '%') " : "")
                        + (CommonUtils.isNotBlank(userinfo.getLoginName()) ? "and login_name = ? " : ""),

                new Object[]{userinfo.getUsername(), userinfo.getLoginName()}
        );
    }

    @Override
    public int updateById(Userinfo userinfo) {
        List<String> sqlList = new ArrayList<>();
        if (userinfo.getUsername() != null) {
            sqlList.add("username = ?");
        }
        if (userinfo.getLoginName() != null) {
            sqlList.add("login_name = ?");
        }
        String collect = String.join(",", sqlList);
        //根据ID跟新信息的方法
        return super.actionExecute(
                "update userinfo set " + collect + " where id = ?",

                new Object[]{userinfo.getUsername(), userinfo.getLoginName(), userinfo.getId()}
        );
    }

    @Override
    public int deleteById(Long id) {
        //根据ID删除信息的方法
        return super.actionExecute("delete from userinfo where id = ?", new Object[]{id});
    }

    @Override
    public int insert(Userinfo userinfo) {
        //插入信息的方法
        return super.actionExecute(
                "insert into userinfo(username, login_name, pwd) " +
                        "values(?, ?, ?)",
                new Object[]{userinfo.getUsername(), userinfo.getLoginName(), userinfo.getPwd()}
        );
    }

    @Override
    public Userinfo queryById(Long id) {
        List<Userinfo> userinfoList = super.queryExecute(
                Userinfo.class,
                "select * from userinfo where id = ?",
                new Object[]{id}
        );
        return userinfoList.isEmpty() ? null : userinfoList.get(0);
    }

    public List<Userinfo> loginSelectList(String loginName, String pwd) {
        return super.queryExecute(
                Userinfo.class,
                "select * from userinfo where login_name = ? and pwd = ?",
                new Object[]{loginName, pwd}
        );
    }
}
